using UnityEngine;

public class BaseMovement : MonoBehaviour {

    [SerializeField]
    float _speed = 1;

    [SerializeField]
    float _drag;

    [SerializeField]
    AnimationCurve _noInputDragCurve = AnimationCurve.Linear(0, 0, 1, 1);

    bool _moveInput;

    #region Properties
    public float Drag {
        get { return _drag; }
        set { _drag = value; }
    }

    Rigidbody2D Rigidbody2DComponent { get; set; }

    public float Speed {
        get { return _speed; }
        set { _speed = value; }
    }
    #endregion

    void Awake() {
        Rigidbody2DComponent = GetComponent<Rigidbody2D>();
    }

    void Update() {
        //if(_moveInput)
        //    Rigidbody2DComponent.drag = Mathf.Clamp(Rigidbody2DComponent.velocity.magnitude * .5f, 0, Drag);
        //else
        Rigidbody2DComponent.drag = _noInputDragCurve.Evaluate(Rigidbody2DComponent.velocity.magnitude) * Drag;
    }

    void LateUpdate() {
        _moveInput = false;
    }

    public void Move(Vector2 direction) {
        direction = Vector2.ClampMagnitude(direction, 1);

        Rigidbody2DComponent.AddForce(direction * Speed * Time.deltaTime, ForceMode2D.Impulse);
        PointInDirection(direction);

        _moveInput = true;
    }

    public void SetVelocity(Vector2 direction) {
        Rigidbody2DComponent.velocity = direction;
    }

    public void PointAt(Vector3 point) {
        PointInDirection(point - transform.position);
    }

    public void PointInDirection(Vector3 direction) {
        float angle = -(Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg);

        if(direction != Vector3.zero)
            Rigidbody2DComponent.rotation = angle;
    }
}